package com.example.mydy.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.mydy.R;
import com.example.mydy.RewardDetailActivity;
import com.example.mydy.SubmitRewardTaskActivity;
import com.example.mydy.adapter.MyRewardAdapter;
import com.example.mydy.model.RewardTask;
import com.example.mydy.utils.MockDataManager;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * 展示用户已接取的悬赏任务列表，可按状态筛选
 */
public class MyRewardsFragment extends Fragment implements MyRewardAdapter.OnMyRewardClickListener {

    // 状态过滤常量
    private static final int FILTER_ALL = 0;
    private static final int FILTER_IN_PROGRESS = 1;
    private static final int FILTER_UNDER_REVIEW = 2;
    private static final int FILTER_COMPLETED = 3;
    private static final int FILTER_REJECTED = 4;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView recyclerView;
    private TextView emptyView;
    private TabLayout statusTabLayout;
    
    private MyRewardAdapter adapter;
    private List<RewardTask> allMyRewards = new ArrayList<>();
    private List<RewardTask> filteredRewards = new ArrayList<>();
    private MockDataManager mockDataManager;
    private int currentFilter = FILTER_ALL;

    public MyRewardsFragment() {
        // 必需的空构造函数
    }

    public static MyRewardsFragment newInstance() {
        return new MyRewardsFragment();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_rewards, container, false);
        
        mockDataManager = MockDataManager.getInstance();
        
        // 初始化视图
        initViews(view);
        
        // 加载数据
        loadMyRewards();
        
        return view;
    }

    private void initViews(View view) {
        // 初始化SwipeRefreshLayout
        swipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        swipeRefreshLayout.setOnRefreshListener(this::loadMyRewards);
        
        // 初始化RecyclerView
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        
        // 初始化空视图
        emptyView = view.findViewById(R.id.empty_view);
        
        // 初始化状态过滤标签页
        statusTabLayout = view.findViewById(R.id.status_tab_layout);
        setupStatusTabs();
        
        // 初始化适配器
        adapter = new MyRewardAdapter(filteredRewards, this);
        recyclerView.setAdapter(adapter);
    }

    private void setupStatusTabs() {
        // 添加状态标签
        statusTabLayout.addTab(statusTabLayout.newTab().setText("全部"));
        statusTabLayout.addTab(statusTabLayout.newTab().setText("进行中"));
        statusTabLayout.addTab(statusTabLayout.newTab().setText("审核中"));
        statusTabLayout.addTab(statusTabLayout.newTab().setText("已完成"));
        statusTabLayout.addTab(statusTabLayout.newTab().setText("已拒绝"));
        
        // 设置标签选择监听器
        statusTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                currentFilter = tab.getPosition();
                filterRewards();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                // 不需要处理
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                // 不需要处理
            }
        });
    }
    
    private void loadMyRewards() {
        swipeRefreshLayout.setRefreshing(true);
        
        // 获取当前用户名
        String username = mockDataManager.getCurrentUsername();
        
        // 从MockDataManager获取用户的所有悬赏任务
        allMyRewards = mockDataManager.getUserRewardTasks(username);
        
        // 应用过滤
        filterRewards();
        
        swipeRefreshLayout.setRefreshing(false);
    }
    
    private void filterRewards() {
        filteredRewards.clear();
        
        switch (currentFilter) {
            case FILTER_ALL:
                // 添加所有任务
                filteredRewards.addAll(allMyRewards);
                break;
            case FILTER_IN_PROGRESS:
                // 添加进行中的任务
                for (RewardTask task : allMyRewards) {
                    if (task.getProgressStatus() == RewardTask.STATUS_IN_PROGRESS) {
                        filteredRewards.add(task);
                    }
                }
                break;
            case FILTER_UNDER_REVIEW:
                // 添加审核中的任务
                for (RewardTask task : allMyRewards) {
                    if (task.getProgressStatus() == RewardTask.STATUS_UNDER_REVIEW) {
                        filteredRewards.add(task);
                    }
                }
                break;
            case FILTER_COMPLETED:
                // 添加已完成的任务
                for (RewardTask task : allMyRewards) {
                    if (task.getProgressStatus() == RewardTask.STATUS_COMPLETED) {
                        filteredRewards.add(task);
                    }
                }
                break;
            case FILTER_REJECTED:
                // 添加已拒绝的任务
                for (RewardTask task : allMyRewards) {
                    if (task.getProgressStatus() == RewardTask.STATUS_REJECTED) {
                        filteredRewards.add(task);
                    }
                }
                break;
        }
        
        // 更新UI
        updateUI();
    }
    
    private void updateUI() {
        if (adapter != null) {
            adapter.updateData(filteredRewards);
        }
        
        // 显示或隐藏空视图
        if (filteredRewards.isEmpty()) {
            emptyView.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }
    
    public void refreshData() {
        if (isAdded()) {
            loadMyRewards();
        }
    }

    @Override
    public void onRewardClick(RewardTask rewardTask) {
        // 打开悬赏详情页
        startActivity(RewardDetailActivity.createIntent(requireContext(), rewardTask.getId()));
    }

    @Override
    public void onSubmitClick(RewardTask rewardTask) {
        // 提交悬赏任务
        Intent intent = new Intent(getContext(), SubmitRewardTaskActivity.class);
        intent.putExtra("taskId", rewardTask.getId());
        startActivity(intent);
    }

    @Override
    public void onCancelClick(RewardTask rewardTask) {
        // 显示确认对话框
        new MaterialAlertDialogBuilder(requireContext())
                .setTitle("取消任务")
                .setMessage("确定要放弃此悬赏任务吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 取消任务
                    boolean success = mockDataManager.cancelRewardTask(
                            mockDataManager.getCurrentUsername(),
                            rewardTask.getId());
                    
                    if (success) {
                        Toast.makeText(getContext(), "已放弃任务", Toast.LENGTH_SHORT).show();
                        // 刷新数据
                        loadMyRewards();
                    } else {
                        Toast.makeText(getContext(), "操作失败，请重试", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
} 